import React, { useState, useRef, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';

interface CustomDropdownProps {
  trigger: React.ReactNode;
  children: React.ReactNode;
  placement?: 'bottomLeft' | 'bottomRight' | 'topLeft' | 'topRight';
  className?: string;
}

const CustomDropdown: React.FC<CustomDropdownProps> = ({
  trigger,
  children,
  placement = 'bottomRight',
  className = ''
}) => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const triggerRef = useRef<HTMLDivElement>(null);

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current && 
        !dropdownRef.current.contains(event.target as Node) &&
        triggerRef.current && 
        !triggerRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 修复位置计算逻辑
  const getPositionStyles = () => {
    if (!triggerRef.current) return {};
    
    const triggerRect = triggerRef.current.getBoundingClientRect();
    const viewportHeight = window.innerHeight;
    const viewportWidth = window.innerWidth;
    
    const styles: React.CSSProperties = {
      position: 'fixed',
      zIndex: 99999, // 大幅提升层级，确保在最顶层
      minWidth: '200px',
      maxWidth: '300px',
      pointerEvents: 'auto' // 确保可以交互
    };

    switch (placement) {
      case 'bottomLeft':
        return {
          ...styles,
          top: triggerRect.bottom + 8,
          left: triggerRect.left
        };
      case 'bottomRight':
        return {
          ...styles,
          top: triggerRect.bottom + 8,
          right: viewportWidth - triggerRect.right
        };
      case 'topLeft':
        return {
          ...styles,
          bottom: viewportHeight - triggerRect.top + 8,
          left: triggerRect.left
        };
      case 'topRight':
        return {
          ...styles,
          bottom: viewportHeight - triggerRect.top + 8,
          right: viewportWidth - triggerRect.right
        };
      default:
        // 默认使用 bottomRight，但确保在视口内
        let top = triggerRect.bottom + 8;
        let right = viewportWidth - triggerRect.right;
        
        // 检查是否超出视口边界
        if (top + 300 > viewportHeight) {
          top = triggerRect.top - 300 - 8; // 显示在上方
        }
        if (right + 300 > viewportWidth) {
          right = viewportWidth - 300 - 16; // 向左偏移
        }
        
        return {
          ...styles,
          top,
          right
        };
    }
  };

  // 调试信息
  if (process.env.NODE_ENV === 'development') {
    console.log('CustomDropdown - isOpen:', isOpen);
    console.log('CustomDropdown - triggerRef:', triggerRef.current);
    console.log('CustomDropdown - dropdownRef:', dropdownRef.current);
  }

  return (
    <div className={`custom-dropdown ${className}`} style={{ position: 'relative', display: 'inline-block' }}>
      <div 
        ref={triggerRef}
        onClick={() => {
          console.log('CustomDropdown clicked, current isOpen:', isOpen);
          setIsOpen(!isOpen);
        }}
        style={{ 
          cursor: 'pointer',
          display: 'inline-block' 
        }}
      >
        {trigger}
      </div>
      
      <AnimatePresence>
        {isOpen && (
          <motion.div
            ref={dropdownRef}
            style={{
              ...getPositionStyles(),
              background: theme.dropdownBackground,
              backdropFilter: 'blur(20px)',
              borderRadius: '12px',
              border: `1px solid ${theme.dropdownBorderColor}`,
              boxShadow: `0 8px 32px ${theme.dropdownShadowColor}`,
              padding: '8px 0',
              overflow: 'hidden'
            }}
            initial={{ opacity: 0, scale: 0.8, y: 10 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.8, y: 10 }}
            transition={{ duration: 0.2, type: 'spring' }}
          >
            {children}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};

export default CustomDropdown;